<?php
class Common {
     /**
     * 生成sql 转义特殊字符
     * @param type $string
     * @return type 
     */
     public static function strEscape($string, $flag=TRUE) {
          if($flag)
          {
            $string = str_replace('"', " ", $string);
          }
          $db=  MysqlDB::load("");
          $con=$db->get_con();
          if(function_exists("mysqli_escape_string")){
             $string =  mysqli_real_escape_string($con,$string);
          }else{
              $string =  mysql_escape_string($string);
          }
        
        return $string;
     }
     static function loadTable($table_name){
         return new MysqlDB($table_name);
     }
     static function getCityInfo($ip){
         $url="http://apistore.baidu.com/microservice/iplookup?ip={$ip}";
         $response=self::Get_Contents($url);
         $json=  json_decode($response,TRUE);
         if($json['errNum']==0){
             return $json["retData"];
         }
         return FALSE;
     }
     /**
      * 生成租房单号函数
      * @param type $id 加入单号里的id值,一般传入租户id
      * 返回租房单号
      */
     static function genOrderNo($id){
         return "OR".$id."-".date("Ymd")."-".time();
     }


     /**
     * 获取当前页面完整URL地址
     */
    static function getUrl() {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? self::safeReplace($_SERVER['PHP_SELF']) : self::safeReplace($_SERVER['SCRIPT_NAME']);
        $path_info = isset($_SERVER['PATH_INFO']) ? self::safeReplace($_SERVER['PATH_INFO']) : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? self::safeReplace($_SERVER['REQUEST_URI']) : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . self::safeReplace($_SERVER['QUERY_STRING']) : $path_info);
        if($_SERVER["REQUEST_METHOD"]=='POST'){
            $querystring = http_build_query($_REQUEST);
            $relate_url="/?".$querystring; 
        }
        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
    }
     /**
     * 读取当前url移除分页参数
     */
    static function getCurrentUrl() {       
          $url = self::getUrl();   
     
          $querystring = substr(strstr($url, '?'), 1);
         
          parse_str($querystring, $pars);
          $query_array = array();
          foreach ($pars as $k => $v) {
              if ($k == 'prev' || $k == 'page' || $k == 'next' || $k == 'pagenum') {
                  continue;
              }
              $query_array[$k] = $v;
          }
 
          $querystring = http_build_query($query_array);
          $pos = strpos($url, '?');
          $url = substr($url, 0, $pos) . '?' . $querystring;
        
        return $url;
    }
    /**
     * 安全过滤函数
     * @param $string
     * @return string
     */
    static function safeReplace($string) {
        $string = str_replace('%20', '', $string);
        $string = str_replace('%27', '', $string);
        $string = str_replace('%2527', '', $string);
        $string = str_replace('*', '', $string);
        $string = str_replace('"', '&quot;', $string);
        $string = str_replace("'", '', $string);
        $string = str_replace('"', '', $string);
        $string = str_replace(';', '', $string);
        $string = str_replace('<', '&lt;', $string);
        $string = str_replace('>', '&gt;', $string);
        $string = str_replace("{", '', $string);
        $string = str_replace('}', '', $string);
        return $string;
    }
    public static function getPages($count, $current_page = 1, $page_size = 20)
    {
        
        $total_pages = ceil($count/$page_size);       
    
        return array(
          'url'        => self::getCurrentUrl(),
          'cur'        => $current_page,
          'count'      => $count,
          'total_pages'=> $total_pages,
          'next'       => $current_page < $total_pages ? $current_page+1 : $current_page,
          'prev'       => $current_page > 1 ? $current_page-1 : 1,
        );
        
        
    }
    //生成缩略图链接地址
    public static function getThumb($picpath,$style){
        $upload=  UploadFile::getInstance();
         global $_G;
         $imagepath="";
         if(isset($_G["upload_image"]["image_path"])){
             $imagepath=$_G["upload_image"]["image_path"];
         }
         
         if(stripos($picpath, $imagepath)!==FALSE){
             $picpath=str_replace($imagepath, "", $picpath);
         }
      
         return $upload->getImageUrl($picpath,$style);
     }
     //获得用户ip地址
     public static function getIp(){
        $onlineip = ''; 
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) { 
        $onlineip = getenv('HTTP_CLIENT_IP'); 
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) { 
        $onlineip = getenv('HTTP_X_FORWARDED_FOR'); 
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) { 
        $onlineip = getenv('REMOTE_ADDR'); 
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) { 
        $onlineip = $_SERVER['REMOTE_ADDR']; 
        }
       
        if($onlineip=="127.0.0.1"||strpos($onlineip, "192.168.")!==FALSE){
            $output = self::Curl_Get('http://www.pinkqueen.com/IpApi.php'); 
          
            $onlineip=$output;
        
        }
        if($onlineip==""){
            $onlineip="127.0.0.1";
        }
        return $onlineip;
     }
     //通过ip获得城市名
     public static function getCityName($ip=''){
         if($ip==''){
             $ip=  self::getIp();
         }
         $output=self::Curl_Get("http://ip.taobao.com/service/getIpInfo.php?ip={$ip}");
         $json= json_decode($output);
         return $json->data->city;
     }

     //获得天气信息
     public static function getWheather($city=""){
         if($city==""){
             $city=  self::getCityName(); 
         }
        
         $output=  self::Curl_Get("http://api.map.baidu.com/telematics/v3/weather?location={$city}&output=json&ak=bg0B6Ab8DSG0l7aeqTSaX3lT");
         $json=  json_decode($output);
         if(isset($json->results[0])){
             return $json->results[0];
         }
         return FALSE;
     }

     //curl get请求
     public static function Curl_Get($url,$referer=""){
         if(function_exists("curl_init")){
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         if($referer!=""){
             curl_setopt($ch, CURLOPT_REFERER, $referer);
         }
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         $output = curl_exec($ch);
         curl_close($ch);
         return $output;
         }else{
             return self::Get_Contents($url);
         }
     }
     //尝试2种请求，curl 和file_get ,get方式
     public static function Get_Contents($url){
        if (ini_get("allow_url_fopen") == "1") {
            $response = file_get_contents($url);
        }else{
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_URL, $url);
            $response =  curl_exec($ch);
            curl_close($ch);
        }

       

        return $response;
    }
     //curl post请求
     public static function Curl_Post($url,$param=array()){
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
         curl_setopt($ch, CURLOPT_VERBOSE, 1);
        // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
         //curl_setopt($ch, CURLOPT_TIMEOUT, 30);
         curl_setopt($ch, CURLOPT_ENCODING, "");
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_POST, 1);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
         $output = curl_exec($ch);
         curl_close($ch);
         return $output;
     }
     
     //租户后台,判断菜单是否被选中
     public static function T_Is_Active($menu_url,$echo="active"){
         $menu_url=strtolower($menu_url);
         $action=array_keys($_REQUEST,0);
      
         if(isset($action[0])){
             $curr_url=  strtolower($action[0]);
             if($menu_url===$curr_url){
                 return $echo;
             }else{
                 
             }
         }
       
     }




     //判断菜单是否为选中状态,是选择状态则输入参数2
     public static function Is_Active($menu_url,$isparent=0,$echo="active"){
        
         $menu_url=strtolower($menu_url);
         $action=array_keys($_REQUEST,0);
         if(isset($action[0])){
             $curr_url=  strtolower($action[0]);
              

             if($menu_url===$curr_url){
                 
                 echo $echo;
                 return;
             }else{
              
                 $admin_menulogic=new MysqlDB("admin_menu");
                 $menucate=  explode("/", $menu_url);
                 if($isparent==0){
                 $menu=$admin_menulogic->get_one("id","c='{$menucate[0]}' and a='{$menucate[1]}' and parent_id=0");
                 }else{
                  $menu=$admin_menulogic->get_one("id","c='{$menucate[0]}' and a='{$menucate[1]}' and parent_id!=0");
                 }
                 $children=  $admin_menulogic->select("c,a","parent_id={$menu["id"]}");
                 foreach($children as $v){
                     if(strtolower($v["c"])."/".strtolower($v["a"])===$curr_url){
                         echo $echo;
                         return;
                     }
                 }
             }
         }
     }
     //计算房租到期时间,有效截止日期,参数1：租房日期,参数2：交租日期，方法1,30天出租日算法
     public static function Effective_Time1($rent_time="",$year_moth=""){
        $start=  $rent_time;
         $endt=strtotime($year_moth);
         $tstart=  getdate($start);
         $tendt=getdate($endt);
         $i=($tendt["year"]-$tstart["year"])*12+$tendt["mon"]-$tstart["mon"];
        $tmp2=$i*30;
        $tmp=strtotime("+{$tmp2} day",$start);
        return $tmp;
     }
     
      //计算房租到期时间,有效截止日期,参数1：租房日期,参数2：交租日期,方法2,固定日期算法,参数3：是否下一个月
     public static function Effective_Time2($rent_time="",$year_moth="",$isnext=TRUE){
         $start= $rent_time;
         $endt=strtotime($year_moth);
         $tstart=  getdate($start);
         $tendt=getdate($endt);
        
         
         if($isnext){
             
         
          $month= ($tendt["mon"]+1)%12;
         
          $year=$tendt["year"]+intval(($tendt["mon"]+1)/12);
          if($month==0){
              $month=12;
              $year=$tendt["year"]+(intval(($tendt["mon"]+1)/12)-1);
           }
         $tendt["year"]=$year;
         $tendt["mon"]=$month;
         
         
         }
        $last= self::GetMonthLastDay($tendt["year"]."-".$tendt["mon"]."-01");
         if($tstart["mday"]>$last){
             return strtotime($tendt["year"]."-".$tendt["mon"]."-".$last);
         }else{
             return strtotime($tendt["year"]."-".$tendt["mon"]."-".$tstart["mday"]);
          
         }
     }
     
     //获取上一个月的年份和月份，参数:时间戳
     public static function GetPreMonth($time){
         $dateinfo=getdate($time);
         $month=0;
         $year=$dateinfo["year"];
          if($dateinfo["mon"]-1==0){
                $month=12;
                $year=$year-1;
          }else{
                $month=$dateinfo["mon"]-1;
          }
          return array("year"=>$year,"month"=>$month);
     }


     //获得月份的最后一天
     public static function GetMonthLastDay($date){
         $firstday = date('Y-m-01', strtotime($date)); 
         $lastday = date('d', strtotime("$firstday +1 month -1 day")); 
         return $lastday; 
     }
     public static function RewriteUrl($c,$a,$arg=""){
         
         global $_G;
         $is_rewrite=$_G["is_rewrite"];
         $rootpath="";
         if(substr(WEBROOT,  strlen(WEBROOT)-1,1)=="/"){
             $rootpath=substr(WEBROOT,0, strlen(WEBROOT)-1);
         }
         if(substr($rootpath,0,1)=="/"){
             $rootpath=  substr($rootpath, 1,  strlen($rootpath));
         }
        
         if($is_rewrite){
             if($rootpath!=""){
                return "/".$rootpath."/".$c."/".$a.$arg;
             }else{
                 return "/".$c."/".$a.$arg;
             }
         }
         return "?".$c."/".$a.$arg;
     }
     //字符串截取
      public static function Cut_Str($string, $sublen, $start = 0, $code = 'UTF-8')
    {
        if($code == 'UTF-8')
        {
            $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
            preg_match_all($pa, $string, $t_string);

            if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
            return join('', array_slice($t_string[0], $start, $sublen));
        }
        else
        {
            $start = $start*2;
            $sublen = $sublen*2;
            $strlen = strlen($string);
            $tmpstr = '';

            for($i=0; $i< $strlen; $i++)
            {
                if($i>=$start && $i< ($start+$sublen))
                {
                    if(ord(substr($string, $i, 1))>129)
                    {
                        $tmpstr.= substr($string, $i, 2);
                    }
                    else
                    {
                        $tmpstr.= substr($string, $i, 1);
                    }
                }
                if(ord(substr($string, $i, 1))>129) $i++;
            }
            if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";
            return $tmpstr;
        }
    }
    
    
    
    public static function Time_Tran($time=0){
         if($time){
            $now=  time();
            $dis=$now-$time;
            if($dis<=0){
                return "刚刚";
            }
            if($dis<60){
                return "{$dis}秒前";
            }else{
                if($dis<3600){
                     return floor($dis/60)."分钟前";
                }else{
                    if($dis<86400){
                        return floor($dis/3600).'小时前';
                    }else{
                        return floor($dis/86400).'天前';
                       
                    }
                }
            }
            
        }else{
            return FALSE;
        }
    }
    
    
     //做跳转,提示跳转
     public static function showmessage($msg,$type = "error",$url='',$timeout=1000){
         if($url!=''){
         $script="<script>setTimeout(function(){window.location.href='{$url}';},{$timeout});</script>";
         $javascript=$url;
         }else{
         $javascript="javascript:void(0);";
         $script="<script>setTimeout(function(){window.history.go(-1);},{$timeout});</script>"; 
         }
         $html="<style>html,body{overflow: hidden;}</style><meta name='viewport' content='width=device-width, initial-scale=1'><div style='float: left;position:relative;min-height:300px;left:50%;margin:30px -140px;padding:10px 10px;width:260px;box-shadow: rgba(0,0,0,.27) 0 1px 3px,#DCDCDC 0 1px 0,#DDD 0 -1px 0;border-radius: 8px;color:#3c763d;font-size: 15px;font-family: Microsoft yahei;'><p style='color:red;'>{$type}:</p><p style='text-align:center;'>{$msg}</p><p style='position:absolute;bottom:0px;width:100%;text-align:center;left:0px;'><a href='{$javascript}' style='text-decoration: none;color:red;'>点击返回</a></p></div>";
        
         echo $html.$script;
     }
}
